package com.link.base.base.appinfo.controller;

import com.link.base.base.appinfo.model.AppMobileInfo;
import com.link.base.base.appinfo.model.AppMobileUser;
import com.link.base.base.appinfo.model.LoadFlag;
import com.link.base.base.appinfo.service.AppMobileInfoService;
import com.link.base.user.model.CoreUser;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.cllog.LCLogger;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * APP设备及部分初始数据接口
 *
 * @author ouyangzhenqiang
 * @date 2018/10/16
 */
@Controller
@RequestMapping("/link/appMobileInfo")
public class AppMobileInfoController extends BasicController<AppMobileInfo> {

    @Resource
    private AppMobileInfoService appMobileInfoService;
    @Resource
    private KeyGenerateService keyGenerateService;

    @Override
    public BasicService<AppMobileInfo> getBasicService() throws Exception {
        return appMobileInfoService;
    }

    /**
     * 获取设备统计数据
     *
     * @author ouyangzhenqiang
     * @date 2019/08/29 10:12
     */
    @PostMapping(value = "/queryDeviceNumber", name = "移动设备统计数据")
    @ResponseBody
    public Map<String, Object> queryDeviceNumber(@JsonParam AppMobileInfo record, HttpSession session,
                                                 HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(8);
        try {
            CoreUser user = UserUtil.getUser();
            record.setPageFlag(false);
            result = appMobileInfoService.queryDeviceNumber(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }
    
    /**
     * 获取设备新增和活跃数据
     * 
     * @author ouyangzhenqiang
     * @date 2019/08/29 10:27
     */
    @PostMapping(value = "/queryNewOrLiveNumber", name = "移动设备新增和活跃数据")
    @ResponseBody
    public Map<String, Object> queryNewOrLiveNumber(@JsonParam AppMobileInfo record, HttpSession session,
                                                 HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(8);
        try {
            record.setPageFlag(false);
            result = appMobileInfoService.queryNewOrLiveNumber(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 获取机型分布
     *
     * @author ouyangzhenqiang
     * @date 2019/08/29 10:27
     */
    @PostMapping(value = "/queryMobileTypeNumber", name = "移动设备机型分布")
    @ResponseBody
    public Map<String, Object> queryMobileTypeNumber(@JsonParam AppMobileInfo record, HttpSession session,
                                                    HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(8);
        try {
            record.setPageFlag(false);
            result = appMobileInfoService.queryMobileTypeNumber(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 获取地区分布
     *
     * @author ouyangzhenqiang
     * @date 2019/08/29 10:27
     */
    @PostMapping(value = "/queryProvinceNumber", name = "移动设备地区分布")
    @ResponseBody
    public Map<String, Object> queryProvinceNumber(@JsonParam AppMobileInfo record, HttpSession session,
                                                     HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(8);
        try {
            record.setPageFlag(false);
            result = appMobileInfoService.queryProvinceNumber(record);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 生成记录Id
     *
     * @author ouyangzhenqiang
     * @date 2018/10/16
     */
    @PostMapping(value = "/getId", name = "生成记录Id")
    @ResponseBody
    public Map<String, Object> getId(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            ArrayList<Long> arrayList = new ArrayList<>();
            int ten = 10;
            for (int i = 0; i < ten; i++) {
                arrayList.add(keyGenerateService.keyGenerate());
            }
            result.put("success", true);
            result.put("result", arrayList);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 生成订单编号
     *
     * @author ouyangzhenqiang
     * @date 2018/10/16
     */
    @GetMapping(value = "/getOrderNoGenerate", name = "生成订单编号")
    @ResponseBody
    public Map<String, Object> getOrderNoGenerate(HttpSession session, HttpServletRequest request,
                                                  HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            List<String> orderCodeListBySize = new ArrayList<>(16);
            for (int i = 0; i < 10; i++) {
                orderCodeListBySize.add(keyGenerateService.keyGenerate().toString());
            }
            result.put("success", true);
            result.put("result", orderCodeListBySize);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 查询数据库检测表，用于判断是否需要重新加载基础数据
     *
     * @author ouyangzhenqiang
     * @date 2018/10/16
     */
    @GetMapping(value = "/getLoadDataFlag", produces = "application/json", name = "移动端判断是否需要重新加载基础数据")
    @ResponseBody
    public Map<String, Object> getLoadDataFlag(HttpSession session, HttpServletRequest request,
                                               HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        LCLogger.info().withMessageKey("getLoadDataFlag").withMessage("开始判断是否需要加载基础数据.").flush();
        try {
            LoadFlag temp = new LoadFlag();
            List<LoadFlag> list = appMobileInfoService.getLoadDataFlag(temp);
            result.put("success", true);
            result.put("result", list);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.toString());
        }
        return result;
    }

    /**
     * 移动设备注册
     *
     * @author ouyangzhenqiang
     * @date 2018/10/16
     */
    @PostMapping(value = "/collectMobile", produces = "application/json", name = "移动设备注册")
    @ResponseBody
    public Map<String, Object> collectClient(@RequestBody AppMobileInfo record,
                                             HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("collectMobile").withMessage("收集客户端信息...").flush();
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            String deviceUuid = record.getUuid();
            String appId = record.getAppId();
            // 使用appId及设备的uuid作为注册判断条件
            if (StringUtils.isNotBlank(deviceUuid) && StringUtils.isNotBlank(appId)) {
                appMobileInfoService.submit(record);
                result.put("success", true);
                result.put("result", "OK");
            } else {
                result.put("success", false);
                if (StringUtils.isBlank(deviceUuid)) {
                    result.put("message", "无法存储客户端信息，原因为设备UUID为空.");
                } else if (StringUtils.isBlank(appId)) {
                    result.put("message", "无法存储客户端信息，原因为设备APPID为空.");
                }
            }
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.toString());
        }
        return result;
    }

    /**
     * 用户点击退出时，清空设备信息表上的用户设备关联关系
     *
     * @author ouyangzhenqiang
     * @date 2018/10/16
     */
    @GetMapping(value = "/clearMobile", produces = "application/json", name = "应用退出登录")
    @ResponseBody
    public Map<String, Object> clearMobile(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("clearMobile").withMessage("清除设备信息上关联的用户信息...").flush();
        Map<String, Object> result = new HashMap<String, Object>(4);

        String uuid = request.getParameter("uuid");
        String appId = request.getParameter("appId");
        String userId = request.getParameter("userId");
        AppMobileInfo mi = new AppMobileInfo();
        mi.setUuid(uuid);
        mi.setAppId(appId);
        mi.setUserId(userId);
        try {
            if (StringUtils.isNotBlank(uuid) && StringUtils.isNotBlank(appId)
                && StringUtils.isNotBlank(userId)) {
                appMobileInfoService.clearUser(mi);
            }
            result.put("success", true);
            result.put("result", "OK");
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("message", e.toString());
        }
        return result;
    }

    /**
     * 获取设备登录历史用户
     *
     * @author ouyangzhenqiang
     * @date 2019/10/23 16:00
     */
    @PostMapping(value = "/mobileUserList", produces = "application/json")
    @ResponseBody
    public Map<String, Object> mobileUserList(@JsonParam QueryParams qps, @JsonParam AppMobileUser entity,
                                              HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>(8);
        try {
            AppMobileUser temp = BasicModel.transformClass(entity, qps);
            List<AppMobileUser> list = appMobileInfoService.mobileUserList(temp);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(temp, list.size()));
            result.put("code", "0");
        }  catch (BasicServiceException e) {
            result.put("success", false);
            result.put("rows", new ArrayList());
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getDetailMessage());
            result.put("code", e.getCode());
        } catch (Exception e) {
            result.put("success", false);
            result.put("rows", new ArrayList());
            result.put("result", e.getMessage());
            result.put("code", "400");
        }
        return result;
    }
}
